package edu.demo.recommend.controller.admin;

import edu.demo.recommend.advice.AdminPermission;
import edu.demo.recommend.common.MD5Utils;
import edu.demo.recommend.common.ResultCodeEnum;
import edu.demo.recommend.exception.RecommendBusinessException;
import edu.demo.recommend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author hb
 */
@Controller
@RequestMapping("/admin/admin")
public class AdminManagerController {
    //使用SpringEL表达式，读取配置文件中的数据为属性进行赋值
    @Value("${admin.email}")
    private String email;
    @Value("${admin.encryptyPassword}")
    private String password;

    @Autowired
    private HttpServletRequest request;

    public static final String ADMIN_NAME_SESSION="admin_name_session";


    @RequestMapping("/loginPage")
    public String loginPage(){
        return "/admin/admin/login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam(name="email") String email,@RequestParam(name="password")  String password){
        if(!StringUtils.hasLength(email) || !StringUtils.hasLength(password)){
            throw new RecommendBusinessException(ResultCodeEnum.NULL_POINT);
        }
        if(email.equals(this.email)&& MD5Utils.md5(password).equals(this.password)){
            //登录成功，将管理的Email封装到Sesion中。
            request.getSession().setAttribute(ADMIN_NAME_SESSION,email);
            //登录成功:redirect表示重定向
             return "redirect:/admin/admin/index";

        }else{
           throw new RecommendBusinessException(ResultCodeEnum.LOGIN_FAIL);
        }

    }

    @Resource
    private UserService userService;

    //表示index的请需要进行权限校验
    @AdminPermission
   // @AdminPermission(produceType = "application/json")
   // @ResponseBody
    @RequestMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("/admin/admin/index");

        int count = userService.countAllUser();
        //封装数据
        mv.addObject("CONTROLLER_NAME","admin");
        mv.addObject("ACTION_NAME","index");
        mv.addObject("userCount",count);
        return mv;
    }
}
